package com.elm.servlet;

import com.elm.controller.*;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 用于分发请求的主要servlet
 */
@WebServlet("/*")
public class DispatcherServlet extends HttpServlet {
    private Map<String, BaseController> controllerMap = new HashMap<>();

    /**
     * 初始化路径分发对应的控制器
     * @param config
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        controllerMap.put("UserController", new UserController());
        controllerMap.put("CartController", new CartController());
        controllerMap.put("OrdersController", new OrdersController());
        controllerMap.put("BusinessController", new BusinessController());
        controllerMap.put("DeliveryAddressController", new DeliveryAddressController());
        controllerMap.put("FoodController", new FoodController());
    }


    /**
     * 处理请求
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getPathInfo();
        System.out.println("get one request : path: " + path);
        if (path == null || path.isEmpty()) {
            resp.sendError(404, "Invalid path");
            return;
        }

        String[] pathPart = path.split("/");
        if (pathPart.length < 1) {
            resp.sendError(404, "Invalid path");
            return;
        }
        //取出相应的实例
        BaseController controller = controllerMap.get(pathPart[1]);
        if (controller == null) {
            resp.sendError(404, "Controller not found");
            return;
        }else {
            //调用相应的方法
            try {
                controller.handleRequest(req, resp);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}